﻿function reloadPage(data) {
    $("#list-search").empty();
    var html = "<table id='dataTables' class='sortable'><thead><tr><th>Account Name</th><th>Full Name</th><th>Department Name</th><th>Language Name</th><th>Score</th><th>Date</th><th>Note</th></tr></thead><tfoot></tfoot><tbody>";
    for (var i = 0; i < data.length; i++) {
        html += "<tr>";
        html += "<td><a class='acc' href='#' data-id='" + data[i].LanguageScoreId + "' data-accountName='" + data[i].AccountName + "'>" + data[i].AccountName + "</a></td>";
        html += "<td>" + data[i].FullName + "</td>";
        html += "<td>" + data[i].DepartmentName + "</td>";
        html += "<td>" + data[i].LanguageName + "</td>";
        html += "<td class='text-right'>" + data[i].Score + "</td>";
        html += "<td class='text-right'>" + formatJSONDate(data[i].Date) + "</td>";
        html += "<td>" + data[i].Note + "</td>";
        html += "</tr>";
    }
    html += "</tbody></table>";
    $("#list-search").html(html);
    $("#dataTables tbody tr td a").click(function () {
        var accountName = $(this).attr("data-accountName");
        var languageId = $(this).attr("data-id");
        details(languageId);
        history(accountName);
        $("#details").bPopup();
    });
}

function listScoreByType(id) {
    $.ajax({
        url: "/LanguageScore/ListLanguageScoreByType",
        type: "POST",
        dataType: "JSON",
        data: { languageTypeId: id },
        success: function (data) {
            reloadPage(data);
        },
        error: function () {
            alert("Error");
        }
    });
}

function details(id) {
    $.ajax({
        url: "/LanguageScore/LanguageScoreDetail",
        type: "POST",
        dataType: "JSON",
        data: { languageScoreId: id },
        success: function (data) {
            $("#history-result").empty();
            var html = "<table width='100%' style='margin-left: 25px;'>";
            html += "<tr><td class='label bold'>Department</td>";
            html += "<td class='control-field'>" + data.DepartmentName + "</td>";
            html += "<td class='label bold'>Account Name</td>";
            html += "<td class='control-field'>" + data.AccountName + "</td></tr>";
            html += "<tr><td class='label bold'>Language Type</td>";
            html += "<td class='control-field'>" + data.LanguageName + "</td>";
            html += "<td class='label bold'>Score</td>";
            html += "<td class='control-field'>" + data.Score + "</td></tr>";
            html += "<tr><td class='label bold'>Date</td>";
            html += "<td class='control-field'>" + formatJSONDate(data.Date) + "</td>";
            html += "<td class='label bold'>Note</td>";
            html += "<td class='control-field'>" + data.Note + "</td></tr></table>";
            $("#history-result").html(html);
        },
        error: function () {
            alert("Error details");
        }
    });
}

function history(id) {
    $.ajax({
        url: "/LanguageScore/ListLanguageScoreHistory",
        type: "POST",
        dataType: "JSON",
        data: { accountName: id },
        success: function (data) {
            $("#list-history").empty();
            var html = "<table class='sortable'' width='100%'>";
            html += "<tr><th>Date</th><th>Account Name</th><th>Language Name</th><th>Score</th><th>Note</th></tr>";
            for (var i = 0; i < data.length; i++) {
                html += "<tr><td>" + formatJSONDate(data[i].Date) + "</td>";
                html += "<td>" + data[i].AccountName + "</td>";
                html += "<td>" + data[i].LanguageName + "</td>";
                html += "<td>" + data[i].Score + "</td>";
                html += "<td>" + data[i].Note + "</td></tr>";
            }
            html += "</table>";
            $("#list-history").html(html);
        },
        error: function () {
            alert("Error history");
        }
    });
}

function search(finalType, fullName, departmentId, statusAccountId, score, accountName, languageScoreTypeId) {
    $.ajax({
        url: '/LanguageScore/Search',
        type: "POST",
        dataType: "JSON",
        data: { finalType: finalType, fullName: fullName, departmentId: departmentId, statusAccountId: statusAccountId, score: score, accountName: accountName, languageTypeId: languageScoreTypeId },
        success: function (data) {
            reloadPage(data);
        },
        error: function () {
            alert("Error");
        }
    });
}

//dataTable custom
var advanceClick = false;
var objTable;
var hidden = '';
var isSelectAll = false;
var totalRecords = 0;

//Initial in Account-Course index
function Initial() {
    $('#selectAll').click(function () {
        isSelectAll = !isSelectAll;
        if (isSelectAll) {
            $('.fields').each(function () {
                $(this).attr('checked', 'checked');
            });
        } else {
            $('.fields').each(function () {
                $(this).attr('checked', false);
            });
        }
    });
    $('#pop').hide();

    $('#details').hide();
    //Show table configuration setting
    $('#setting').click(function () {
        $('#pop').bPopup();
    });
    //Close table configuration
    $('#cancelBtn').click(function () {
        $('#pop').bPopup().close();
    });

}

//Close popup
function ClosePopup(senderId, popId) {
    $('#' + senderId).click(function () {
        $('#' + popId).bPopup().close();
    });
}

//Create Datatable 
function CreateDataTableById(id, columns, wrapper) {
    var cols = [];
    var arr = columns.split(',');
    for (var i = 0; i < arr.length; i++) {
        cols.push({
            "aTargets": [parseInt(arr[i])],
            "bVisible": false
        });
    }

    var obj = $("#" + id).dataTable(
        {
            "sDom": '<"wrapper"tpli>',
            "aLengthMenu": [[20, 50, 100, -1], [20, 50, 100, "All"]],
            "iDisplayLength": 20,
            "sPaginationType": "full_numbers",
            "aaSorting": [[5, "desc"]],
            "aoColumnDefs": cols,
            "bDestroy": true
        });


    $('.' + wrapper).addClass('configurationPaging');

    //$("#search").on("click", function () {
    //    getDataFromDatabase('dataTables', 1, 80);
    //});
    return obj;
}

//Hidden columns: hideColumns is list of columns which will hide : '1,4,6'
function ChangeTableConfiguration(senderId, tableId, columns, wrapper, popId, pageNumber, pageSize, totals) {
    $('#' + senderId).click(function () {
        var current = $('.paginate_active').text();
        currentPage = current;
        hidden = getColumnsHide(columns);
        try { CreateDataTableById(tableId, hidden, wrapper); }
        catch (e) {
            CreateDataTableById(tableId, hidden, wrapper);
        }

        $('#' + popId).bPopup().close();
        configurationPaging(tableId, pageNumber, pageSize, totals);
        setCurrentPage(current, tableId);
        showTotalRecords(tableId, current, pageSize, totals);
    });
}

//get list of columns will hide ( not checked )
function getColumnsHide(className) {
    var hidden = '';
    $('.' + className).each(function (i) {
        if ($(this).prop('checked') == false) {
            hidden += i + ',';
        }
    });
    hidden += '7';
    return hidden;
}

//Paging configuration - IMPORTANT
function CreatePagingNumber(number, size, totals) {
    var page = Math.round(totals / size);
    if (eval(totals) % eval(size) > 0) page++;
    if (page > 0) {
        $('#dataTables_paginate span').html('');
        for (var i = 1; i <= page; i++) {
            $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">' + (i) + '</a>');
            if (i == 5) {
                $('#dataTables_paginate span').append('<a class="paginate_button" tabindex="0">...</a>');
                break;
            }
        }
        $('#dataTables_paginate span a:eq(' + number + ')').removeClass('paginate_button');
        $('#dataTables_paginate span a:eq(' + number + ')').addClass('paginate_active');
    }
}

function getDataFromDatabase(idTable, pageNumber, pageSize) {
    var finalType = $("input[name='chooseScore']").val();
    var fullName = $("#fullName").val();
    var departmentId = $("#department").val();
    var statusAccountId = $("#statusAccount").val();
    var score = $("#score").val();
    var accountName = $("#accountName").val();
    var languageTypeId = $("#tree li .selected").attr("data-id");
    $.ajax({
        "dataType": 'JSON',
        "type": "POST",
        "url": "/LanguageScore/Search",
        "data": {
            currentPage: pageNumber,
            pageSize: pageSize,
            accountName: accountName,
            fullName: fullName,
            departmentId: departmentId,
            statusAccountId: statusAccountId,
            score: score,
            finalType: finalType,
            languageTypeId: languageTypeId
        },
        "success": function (result) {
            var old = null;
            if (objTable.fnGetData(0) != null) {
                old = objTable.fnGetData(0)[7];
            }
            window.objTable.fnClearTable();
            var a;
            for (var i = 0; i < result.length; i++) {
                window.objTable.fnAddData([
                    "<a class='acc' href='javascript:;' data-id='" + result[i].LanguageScoreId + "' data-accountName='" + result[i].AccountName + "'>" + result[i].AccountName + "</a></td>",
                    result[i].FullName,
                    result[i].DepartmentName,
                    result[i].LanguageName,
                    result[i].Score,
                    formatJSONDate(result[i].Date),
                    result[i].Note,
                    result[i].TotalRow
                ]);
                a = result[i].TotalRow;
            }
            if (objTable.fnGetData(0)[7] != old) {
                configurationPaging('dataTables', 0, $('#dataTables_length option:selected').text(), a);
            }
            showTotalRecords(idTable, pageNumber - 1, pageSize, a);

            $("#dataTables tbody tr td a").click(function () {
                var accountName1 = $(this).attr("data-accountName");
                var languageId = $(this).attr("data-id");
                details(languageId);
                history(accountName1);
                $("#details").bPopup();
            });
        }
    });
}
